package com.atwisdom.star.docs.business.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.atwisdom.star.common.util.JsonUtil;
import com.atwisdom.star.common.vo.JsonResult;
import com.atwisdom.star.common.vo.ResultInfo;
import com.atwisdom.star.core.dao.pojo.functionClass.Documents;
import com.atwisdom.star.core.dsl.functionClass.Impl.DocumentsDslServiceImpl;
import com.atwisdom.star.docs.business.DocsBslService;
import com.atwisdom.star.exception.pojo.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

@Service
public class DocsBslServiceImpl implements DocsBslService {


    @Value("${filePath}")
    private String baseFilePath;

    @Autowired
    private DocumentsDslServiceImpl documentsDslService;

    /**
     * 批量上传文件
     * @param files 文件
     * @return 返回结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public ResultInfo<?> uploadFiles(@RequestParam MultipartFile[] files) throws BusinessException{
        try {
            List<JSONObject> listDocument = new ArrayList<>();
            for(int i=0; i<files.length; i++){
                listDocument.add(new JSONObject());
            }
            listDocument = documentsDslService.batchAdd(listDocument);
            List<JSONObject> updDocuments = new ArrayList<>();
            for(int i=0; i<files.length; i++) {
                JSONObject documents = listDocument.get(i);
                MultipartFile file = files[i];
                updDocuments.add(uploadFileById(file, documents.getString("id")));
            }
            listDocument =  documentsDslService.batchUpdate(listDocument);
            return JsonResult.success(listDocument);
        } catch (Exception e) {
            throw new BusinessException("999999", "上传失败", e);
        }
    }
    /**
     * 上传文件
     * @param file 文件
     * @return 返回结果
     */
    @Override
    public ResultInfo<?> uploadFile(@RequestParam MultipartFile file, @RequestParam String id) throws BusinessException{
        JSONObject documents = this.uploadFileById(file,id);
        return JsonResult.success(documentsDslService.update(documents));
    }

    /**
     * 根据文件和id上传文件
     * @param file
     * @param id
     * @return
     */
    private JSONObject uploadFileById(MultipartFile file, String id){
        try {
            if (file.isEmpty()) {
                throw new BusinessException("500", "文件为空");
            }
            String fileName = file.getOriginalFilename();
            String preName = fileName.substring(0,fileName.lastIndexOf("."));
            String suffixName = fileName.substring(fileName.lastIndexOf(".")+1);
            String filePath = baseFilePath+id+"/";
            String path = filePath + fileName;
            File dest = new File(new File(path).getAbsolutePath());//
            if (dest.getParentFile().exists()) {
                FileSystemUtils.deleteRecursively(dest.getParentFile());
            }
            dest.getParentFile().mkdirs();
            file.transferTo(dest);
            return JsonUtil.buildJson(new Object[]{"id",id,"fileName",preName,"extendName",suffixName,"filePath",filePath});
        } catch (Exception e) {
            throw new BusinessException("999999", "上传错误", e);
        }
    };

    /**
     * 下载文件
     * @param documents 文档参数
     * @return 返回值
     */
    @Override
    public ResultInfo<?> downloadFile(Documents documents) throws BusinessException{
        String filePath = getFilePath(documents);
        String base64 = null;
        InputStream in = null;
        try {
            File file = new File(filePath);
            in = new FileInputStream(file);
            byte[] bytes=new byte[(int)file.length()];
            in.read(bytes);
            base64 = Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("500", "下载异常", e);
        }finally {
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new BusinessException("500", "下载异常", e);
                }
            }
        }
        return JsonResult.success(base64);
    }

    private String getFilePath(Documents documents){
        String fileName = validateEmpty(documents.getFileName(),"fileName");// 文件名
        String id = validateEmpty(String.valueOf(documents.getId()),"id");
        String extendName = validateEmpty(documents.getExtendName(),"extendName");
        String filePath = baseFilePath+id+"/"+fileName+"."+extendName;
        return filePath;
    }

    private String validateEmpty(String str,String key){
        if(StrUtil.isEmpty(str)){
            throw new BusinessException("500",key+"参数不能为空");
        }
        return str;
    }

    /**
     * 下载文件
     * @param id 文档参数
     * @return 返回值
     */
    @Override
    public ResultInfo<?> downloadFileById(String id) throws BusinessException{
        //保存文档内容，返回保存好的文档内容
        List<JSONObject> list = documentsDslService.queryByIds(Arrays.asList(Long.valueOf(id)));
        if(list.size()>0){
            Documents documents = JsonUtil.toJavaBean(list.get(0), Documents.class);
            String fileName = documents.getFileName();// 文件名
            if (fileName != null) {
                String filePath = baseFilePath+documents.getId()+"/"+fileName+"."+documents.getExtendName();
                String base64 = null;
                InputStream in = null;
                try {
                    File file = new File(filePath);
                    in = new FileInputStream(file);
                    byte[] bytes=new byte[(int)file.length()];
                    in.read(bytes);
                    base64 = Base64.getEncoder().encodeToString(bytes);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new BusinessException("999999", "业务数据操作异常", e);
                }finally {
                    if(in!=null){
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                            throw new BusinessException("999999", "业务数据操作异常", e);
                        }
                    }
                }
                return JsonResult.success(JsonUtil.buildJson(new Object[]{"documents",documents,"data",base64}));
            }
            return JsonResult.error(200,"下载文件失败,文件未上传！！");
        }
        return JsonResult.error(200,"下载文件失败！！");
    }

    /**
     * 下载文件
     * @param documents 文档参数
     * @return 返回值
     */
    @Override
    public ResultInfo<?> deleteFile(Documents documents) throws BusinessException{
        delFileByDocuments(documents);
        return JsonResult.success("处理成功");
    }
    /**
     * 删除文件
     * @param id 文档参数
     * @return 返回值
     */
    @Override
    public ResultInfo<?> deleteFileById(String id) throws BusinessException{
        JSONObject documents = this.queryById(id);
        delFileByDocuments(JsonUtil.toJavaBean(documents, Documents.class));
        return JsonResult.success("删除成功");
    }

    /**
     * 删除文件
     * @param documents
     */
    private void delFileByDocuments(Documents documents) {
        String filePath = baseFilePath + documents.getId() + "/";
        String path = filePath + documents.getFileName();
        File dest = new File(new File(path).getAbsolutePath());//
        if (dest.getParentFile().exists()) {
            FileSystemUtils.deleteRecursively(dest.getParentFile());
        }
    }

    /**
     * 根据id查询文件列表数据
     * @param id
     * @return
     */
    private JSONObject queryById(String id){
        List<JSONObject> list = documentsDslService.queryByIds(Arrays.asList(Long.valueOf(id)));
        if(list.size()>0) {
            if(CollectionUtil.isNotEmpty(list)){
                return list.get(0);
            }else{
                return null;
            }
        }else{
            throw new BusinessException("500", id+"，数据不存在！");
        }
    }
}
